package com.gmp.product.controller;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.gmp.common.annotation.Log;
import com.gmp.common.core.controller.BaseController;
import com.gmp.common.core.domain.AjaxResult;
import com.gmp.common.enums.BusinessType;
import com.gmp.product.domain.ProductionOrder;
import com.gmp.product.service.IProductionOrderService;
import com.gmp.common.utils.poi.ExcelUtil;
import com.gmp.common.core.page.TableDataInfo;

/**
 * 生产指令Controller
 *
 * @author Koi
 * @date 2025-09-23
 */
@RestController
@RequestMapping("/product/order")
@Api(tags = "生产指令管理")
public class ProductionOrderController extends BaseController {
    @Autowired
    private IProductionOrderService productionOrderService;

    /**
     * 查询生产指令列表
     */
    @PreAuthorize("@ss.hasPermi('product:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(ProductionOrder productionOrder) {
        startPage();
        List<ProductionOrder> list = productionOrderService.selectProductionOrderList(productionOrder);
        return getDataTable(list);
    }

    /**
     * 导出生产指令列表
     */
    @PreAuthorize("@ss.hasPermi('product:order:export')")
    @Log(title = "生产指令", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ProductionOrder productionOrder) {
        List<ProductionOrder> list = productionOrderService.selectProductionOrderList(productionOrder);
        ExcelUtil<ProductionOrder> util = new ExcelUtil<ProductionOrder>(ProductionOrder.class);
        util.exportExcel(response, list, "生产指令数据");
    }

    /**
     * 获取生产指令详细信息
     */
    @PreAuthorize("@ss.hasPermi('product:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(productionOrderService.selectProductionOrderById(id));
    }

    /**
     * 新增生产指令
     */
    @PreAuthorize("@ss.hasPermi('product:order:add')")
    @Log(title = "生产指令", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ProductionOrder productionOrder) {
        // 简单校验产业类型
        String industry = productionOrder.getGmpIndustry();
        if (industry == null || industry.trim().isEmpty()) {
            return AjaxResult.error("产业类型不能为空");
        }

        // 产业类型首字母映射
        String typeCode;
        switch (industry) {
            case "生物医药":
                typeCode = "SW";
                break;
            case "食品":
                typeCode = "SP";
                break;
            case "医疗器械":
                typeCode = "YQ";
                break;
            default:
                return AjaxResult.error("不支持的产业类型：" + industry);
        }

        // 生成时间字符串
        String timeStr = new SimpleDateFormat("yyyyMMddHH").format(new Date());
        String dateStr = new SimpleDateFormat("yyyyMMdd").format(new Date());

        // 静态计数器（实际应用中应使用全局缓存如Redis）
        // 注意：这里仅为示例，实际项目中需要将这些计数器移至方法外或使用缓存
        Map<String, Integer> orderCounter = new ConcurrentHashMap<>();
        Map<String, Integer> batchCounter = new ConcurrentHashMap<>();
        Map<String, Integer> workOrderCounter = new ConcurrentHashMap<>();

        // 生成生产指令编号(order_code) - 原有逻辑
        String orderKey = typeCode + timeStr.substring(0, 8);
        int orderSeq = orderCounter.getOrDefault(orderKey, 0) + 1;
        orderCounter.put(orderKey, orderSeq);
        String orderCode = typeCode + timeStr + String.format("%03d", orderSeq);

        // 生成产品批号(product_code) - 原有逻辑
        // 直接生成3-4位随机数字（不依赖产品名称）
        Random random = new Random();
        int min = 100;   // 最小3位数
        int max = 9999;  // 最大4位数
        int randomNum = min + random.nextInt(max - min + 1);
        String productAbbr = String.valueOf("CP"+randomNum);


        String batchKey = productAbbr + dateStr;
        int batchSeq = batchCounter.getOrDefault(batchKey, 0) + 1;
        batchCounter.put(batchKey, batchSeq);
        String productCode = productAbbr + dateStr + String.format("%02d", batchSeq);

        // 生成派单编码(workOrderCode) - 新增逻辑
        // 规则：WD + 产业类型代码 + 日期 + 车间编码(前2位) + 3位序号(每日重置)
        String workOrderPrefix = "WD"; // 派单固定前缀
        // 获取车间编码，取前2位，不足则补0
        String roomCode = productionOrder.getRoomCode() != null ? productionOrder.getRoomCode() : "";
        String roomAbbr = roomCode.length() >= 2 ? roomCode.substring(0, 2).toUpperCase() : "00";

        // 派单计数器键：产业类型+日期+车间缩写
        String workOrderKey = typeCode + dateStr + roomAbbr;
        int workOrderSeq = workOrderCounter.getOrDefault(workOrderKey, 0) + 1;
        workOrderCounter.put(workOrderKey, workOrderSeq);

        // 组合派单编码
        String workOrderCode = workOrderPrefix + typeCode + dateStr + roomAbbr +
                String.format("%03d", workOrderSeq);

        // 设置编号和默认值
        productionOrder.setOrderCode(orderCode);
        productionOrder.setProductCode(productCode);
        productionOrder.setWorkOrderCode(workOrderCode); // 设置派单编码
        productionOrder.setCreateTime(new Date());
        productionOrder.setUpdateTime(new Date());
        productionOrder.setOrderStatus(productionOrder.getOrderStatus() == null ? (byte) 0 : productionOrder.getOrderStatus());
        productionOrder.setProductionStatus(productionOrder.getProductionStatus() == null ? (byte) 0 : productionOrder.getProductionStatus());
        productionOrder.setIsDelete(0);

        //设置指令审核状态 0-待审核
        productionOrder.setOrderStatus(0L);
        //设置派单状态 0-待派单
        productionOrder.setProductionStatus(0L);

        return toAjax(productionOrderService.save(productionOrder));
    }

    /**
     * 修改生产指令
     */
    @PreAuthorize("@ss.hasPermi('product:order:edit')")
    @Log(title = "生产指令", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ProductionOrder productionOrder) {
        return toAjax(productionOrderService.updateProductionOrder(productionOrder));
    }

    /**
     * 删除生产指令
     */
    @PreAuthorize("@ss.hasPermi('product:order:remove')")
    @Log(title = "生产指令", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(productionOrderService.removeBatchByIds(Arrays.asList(ids)));
    }

    //根据生产指令编码查询生产指令信息
    @ApiOperation("根据生产指令编码查询生产指令信息")
    @GetMapping("/getOrderByCode/{orderCode}")
    @PreAuthorize("@ss.hasPermi('product:getOrderByCode:orderCode')")
    public AjaxResult getOrderByCode(@PathVariable String orderCode) {
        LambdaQueryWrapper<ProductionOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductionOrder::getOrderCode, orderCode);
        ProductionOrder productionOrder = productionOrderService.getOne(queryWrapper);
        return AjaxResult.success(productionOrder);
    }
}
